package top.frsf.object.plant;

import top.frsf.action.TimeAttackAble;
import top.frsf.enums.BulletTypeEnum;
import top.frsf.factory.BulletFactory;
import top.frsf.object.AnimatedGameObject;
import top.frsf.object.GameObject;
import top.frsf.object.bullet.BulletObject;
import top.frsf.object.env.Grass;
import top.frsf.object.zombie.ZomObject;
import top.frsf.starter.impl.BulletStarter;
import top.frsf.starter.impl.EnvStarter;
import top.frsf.starter.impl.PlantStarter;
import top.frsf.starter.impl.ZomStarter;

import java.awt.*;

import static top.frsf.panel.GamePanel.starterContext;

/**
 * 植物基类
 *
 * @author FRSF
 * @since 2025/8/3 0:28
 */
public abstract class PlantObject extends AnimatedGameObject implements TimeAttackAble {
    /**
     * 生命值
     */
    protected int hp;
    /**
     * 子弹类型
     */
    protected BulletTypeEnum bulletType;

    /**
     * @param img        图片
     * @param x          x坐标
     * @param y          y坐标
     * @param width      宽度
     * @param height     高度
     * @param hp         生命值
     * @param bulletType 子弹类型
     */
    public PlantObject(String img, int x, int y, int width, int height, int hp, BulletTypeEnum bulletType) {
        super(img, x, y, width, height);
        this.hp = hp;
        this.bulletType = bulletType;
    }

    @Override
    public void paintSelfImage(Graphics g) {
        super.paintSelfImage(g);
        attack(null);
        g.setColor(Color.RED);
        g.drawString("HP: " + hp, getX() + 10, getY() - 10);
    }

    @Override
    public void performAttack(GameObject  target) {
        ZomStarter zomStarter = starterContext.getStarter(ZomStarter.class);
        BulletStarter bulletStarter = starterContext.getStarter(BulletStarter.class);
        for (ZomObject zomObject : zomStarter.getZomList()) {
            double abs = Math.abs(getRectangle().getCenterY() - zomObject.getRectangle().getCenterY());
            // 是否同一行存在zom
            if (abs < 30) {
                BulletObject bullet = BulletFactory.createBullet(bulletType, getX() + getWidth() - 8, getY() + 5);
                bulletStarter.pesBulls.add(bullet);
                break;
            }
        }
    }

    /**
     * 减血
     *
     * @param hp 减血数
     */
    public void downHp(int hp) {
        this.hp -= hp;
        if (this.hp <= 0) {
            // 移除自身
            PlantStarter plantStarter = starterContext.getStarter(PlantStarter.class);
            EnvStarter envStarter = starterContext.getStarter(EnvStarter.class);
            plantStarter.getDeadPlants().add(this);
            // 恢复草地
            for (Grass grass : envStarter.getGrids()) {
                if (grass.getRectangle().contains(getRectangle())) {
                    grass.setAllowPlant(true);
                    break;
                }
            }
        }
    }
}
